// SmarTest Studio - 设备选择器类

/**
 * DeviceSelector 类 - 管理设备选择相关的所有功能
 */
class DeviceSelector {
    constructor(options = {}) {
        // 配置选项
        this.options = {
            deviceSelectElement: options.deviceSelectElement,
            deviceFrameElement: options.deviceFrameElement,
            uiTreeElement: options.uiTreeElement,
            onDeviceSelected: options.onDeviceSelected || (() => {}),
            onUiTreeUpdate: options.onUiTreeUpdate || (() => {}),
            onError: options.onError || (() => {})
        };
        
        // 初始化UiViewer
        if (options.uiViewer) {
            this.uiViewer = options.uiViewer;
        }
        
        // 状态属性
        this.currentWebRTCClient = null;
        this.deviceSocket = null;
        
        // 初始化
        this.init();
    }
    
    /**
     * 初始化设备选择器
     */
    init() {
        this.initDeviceSelect();
        this.initRefreshButton();
    }
    
    /**
     * 初始化设备选择下拉框功能
     */
    initDeviceSelect() {
        // 初始加载设备列表
        this.loadDeviceList();
        
        // 建立WebSocket连接
        this.initDeviceWebSocket();
        
        // 设置WebSocket事件监听
        this.setupDeviceSocketListeners();
        
        // 设备选择事件处理
        if (this.options.deviceSelectElement) {
            this.options.deviceSelectElement.addEventListener('change', (e) => {
                const selectedValue = e.target.value;
                const selectedOption = e.target.options[e.target.selectedIndex];
                selectedOption.textContent = selectedOption.textContent;
                
                // 如果存在当前的 WebRTCClient 实例，先断开连接
                if (this.currentWebRTCClient) {
                    this.currentWebRTCClient.webrtc_disconnect()
                        .then(() => {
                            this.currentWebRTCClient = null;
                            this.handleDeviceSelection(selectedValue);
                        })
                        .catch(error => {
                            console.error('断开 WebRTC 连接失败:', error);
                            this.currentWebRTCClient = null;
                            this.handleDeviceSelection(selectedValue);
                        });
                } else {
                    this.handleDeviceSelection(selectedValue);
                }
            });
        }
    }
    
    /**
     * 处理设备选择
     * @param {string} selectedValue - 选中的设备值
     */
    handleDeviceSelection(selectedValue) {
        const { deviceFrameElement, uiTreeElement } = this.options;
        
        if (selectedValue === '0') {
            // 如果选择了"请选择设备"，清空设备框架
            if (deviceFrameElement) {
                deviceFrameElement.innerHTML = '';
                deviceFrameElement.classList.remove('has-image', 'landscape-mode', 'portrait-mode');
                deviceFrameElement.style.width = '';
                deviceFrameElement.style.height = '';
            }
            
            // 清空UI控件树
            if (uiTreeElement) {
                this.showUiTreeWarning('请先选择设备');
            }
            
            // 通知外部组件
            this.options.onDeviceSelected(null);
            return;
        }
        
        // 显示加载状态
        this.showDeviceLoading('正在连接设备...');
        this.showUiTreeLoading();
        
        // 创建视频元素
        const videoElement = this.createVideoElement();
        
        // 创建 WebRTCClient 实例
        this.createWebRTCClient(selectedValue, videoElement);
        
        // 连接到设备服务器
        if (deviceFrameElement) {
            deviceFrameElement.innerHTML = '';
            deviceFrameElement.appendChild(videoElement);
        }
        
        this.currentWebRTCClient.webrtc_connect(videoElement);
        
        // 通知外部组件
        this.options.onDeviceSelected(selectedValue);
    }
    
    /**
     * 创建视频元素
     * @returns {HTMLVideoElement} 视频元素
     */
    createVideoElement() {
        const videoElement = document.createElement('video');
        videoElement.autoplay = true;
        videoElement.playsInline = true;
        videoElement.style.width = '100%';
        videoElement.style.height = '100%';
        videoElement.style.objectFit = 'fill';
        return videoElement;
    }
    
    /**
     * 创建WebRTCClient实例
     * @param {string} selectedValue - 设备序列号
     * @param {HTMLVideoElement} videoElement - 视频元素
     */
    createWebRTCClient(selectedValue, videoElement) {
        const { uiTreeElement } = this.options;
        
        this.currentWebRTCClient = new WebRTCClient({
            deviceSn: selectedValue,
            host: window.location.hostname,
            port: window.location.port || (window.location.protocol === 'https:' ? 443 : 80),
            onVideoFrame: () => {
                // 视频帧回调
            },
            onUiTree: (uiTreeData) => {
                // UI 控件树回调
                this.renderUiElementTree(uiTreeData, uiTreeElement);
                this.options.onUiTreeUpdate(uiTreeData);
            },
            onConnected: () => {
                console.log('WebRTC 连接成功');
                this.handleWebRTCConnected(videoElement);
            },
            onDisconnected: () => {
                console.log('WebRTC 连接断开');
            },
            onError: (error) => {
                console.error('WebRTC 错误:', error);
                this.showDeviceError(error);
                this.showUiTreeWarning('获取 UI 控件树失败，请检查设备连接状态');
                this.options.onError(error);
            }
        });
    }
    
    /**
     * 处理WebRTC连接成功
     * @param {HTMLVideoElement} videoElement - 视频元素
     */
    handleWebRTCConnected(videoElement) {
        const { deviceFrameElement } = this.options;
        
        // 设置设备框架尺寸
        const videoTrack = videoElement.srcObject.getVideoTracks()[0];
        if (videoTrack) {
            const settings = videoTrack.getSettings();
            const aspectRatio = settings.width / settings.height;
            
            this.setDeviceFrameSize(aspectRatio > 1);
            if (deviceFrameElement) {
                deviceFrameElement.classList.add('has-image');
            }
        }
    }
    
    /**
     * 设置设备框架尺寸
     * @param {boolean} isLandscape - 是否为横屏
     */
    setDeviceFrameSize(isLandscape) {
        const { deviceFrameElement } = this.options;
        if (!deviceFrameElement) return;
        
        if (isLandscape) {
            // 横屏
            deviceFrameElement.style.width = '640px';
            deviceFrameElement.style.height = '360px';
            deviceFrameElement.classList.add('landscape-mode');
            deviceFrameElement.classList.remove('portrait-mode');
        } else {
            // 竖屏
            deviceFrameElement.style.width = '320px';
            deviceFrameElement.style.height = '640px';
            deviceFrameElement.classList.add('portrait-mode');
            deviceFrameElement.classList.remove('landscape-mode');
        }
    }
    
    /**
     * 显示设备加载状态
     * @param {string} message - 加载消息
     */
    showDeviceLoading(message) {
        const { deviceFrameElement } = this.options;
        if (!deviceFrameElement) return;
        
        deviceFrameElement.innerHTML = `<div class="text-center p-5"><div class="spinner-border" role="status"></div><p class="mt-2">${message}</p></div>`;
        deviceFrameElement.classList.remove('has-image');
    }
    
    /**
     * 显示设备错误
     * @param {string} error - 错误信息
     */
    showDeviceError(error) {
        const { deviceFrameElement } = this.options;
        if (!deviceFrameElement) return;
        
        deviceFrameElement.innerHTML = `<div class="alert alert-danger"><i class="bi bi-exclamation-triangle me-2"></i>${error}</div>`;
        deviceFrameElement.classList.remove('has-image', 'landscape-mode', 'portrait-mode');
        deviceFrameElement.style.width = '';
        deviceFrameElement.style.height = '';
        
        this.options.onError(error);
    }
    
    /**
     * 显示UI树加载状态
     */
    showUiTreeLoading() {
        const { uiTreeElement } = this.options;
        if (uiTreeElement) {
            uiTreeElement.innerHTML = `<div class="loading-indicator"><i class="bi bi-arrow-repeat spin"></i> 正在加载控件树...</div>`;
        }
    }
    
    /**
     * 显示UI树警告
     * @param {string} message - 警告消息
     */
    showUiTreeWarning(message) {
        const { uiTreeElement } = this.options;
        if (uiTreeElement) {
            uiTreeElement.innerHTML = `<div class="alert alert-warning"><i class="bi bi-exclamation-triangle me-2"></i>${message}</div>`;
        }
    }
    
    /**
     * 回退到传统方式获取设备截图
     * @param {string} deviceSn - 设备序列号
     */
    fallbackToTraditionalScreenshot(deviceSn) {
        console.log('回退到传统方式获取设备截图');
        
        // 加载UI控件树
        this.loadUiElementTree(deviceSn);
        
        // 显示加载状态
        this.showDeviceLoading('正在获取设备截图...');
        
        window.http.get(`/api/devices?api=capture_screen&sn=${deviceSn}&filename=screen.jpeg`)
            .then(response => {
                this.handleScreenshotResponse(response);
            })
            .catch(error => {
                this.handleScreenshotError(error);
            });
    }
    
    /**
     * 处理截图响应
     * @param {Object} response - 响应对象
     */
    handleScreenshotResponse(response) {
        const { deviceFrameElement } = this.options;
        if (!deviceFrameElement) return;
        
        if (response.data && response.data.imageUrl) {
            const imageUrl = response.data.imageUrl;
            console.log('Image URL:', imageUrl);
            
            // 创建图片元素来检测纵横比
            const img = new Image();
            img.onload = () => {
                const aspectRatio = img.naturalWidth / img.naturalHeight;
                this.setDeviceFrameSize(aspectRatio > 1);
                
                // 设置图片内容
                deviceFrameElement.innerHTML = `<img src="${imageUrl}" alt="Device Screenshot" style="width: 100%; height: 100%; object-fit: fill;">`;
                deviceFrameElement.classList.add('has-image');
            };
            
            img.onerror = () => {
                this.showDeviceError('图片加载失败');
            };
            
            img.src = imageUrl;
        } else if (response.data && response.data.message) {
            this.showDeviceError(response.data.message);
        } else {
            this.showDeviceError('获取设备截图失败，请检查设备连接状态');
        }
    }
    
    /**
     * 处理截图错误
     * @param {Error} error - 错误对象
     */
    handleScreenshotError(error) {
        console.error('Error fetching screenshot:', error);
        
        let errorMessage = '获取设备截图失败';
        
        // 检查是否有详细错误信息
        if (error.response && error.response.data) {
            if (error.response.data.message) {
                errorMessage = error.response.data.message;
            } else if (typeof error.response.data === 'string') {
                errorMessage = error.response.data;
            }
        } else if (error.message && error.message.includes('Network Error')) {
            errorMessage = '网络连接错误，请检查服务器状态';
        } else if (error.message) {
            errorMessage = error.message;
        }
        
        // 如果错误信息包含ZMQ，提供更具体的指导
        if (errorMessage.includes('ZMQ')) {
            errorMessage = `ZMQ通信错误: ${errorMessage}。请确保设备服务器已启动并正常运行。`;
        }
        
        this.showDeviceError(errorMessage);
    }
    
    /**
     * 加载设备列表
     */
    loadDeviceList() {
        const { deviceSelectElement } = this.options;
        if (!deviceSelectElement) return;
        
        // 加载设备列表
        window.http.get('/api/devices?api=load_devices')
            .then(response => {
                // 渲染设备选项
                const devices = response.data;
                let options = '<option value="0" selected>请选择设备</option>';
                devices.forEach(device => {
                    options += `<option value="${device.sn}">${device.name} (${device.status})</option>`;
                });
                
                deviceSelectElement.innerHTML = options;
            })
            .catch(error => {
                console.error('加载设备列表出错:', error);
                deviceSelectElement.innerHTML = '<option value="">加载设备失败</option>';
            });
    }
    
    /**
     * 初始化设备WebSocket连接
     */
    initDeviceWebSocket() {
        // 检查全局deviceSocket实例是否存在
        if (typeof deviceSocket === 'undefined') {
            console.warn('SocketIOClient not available, skipping WebSocket initialization');
            return;
        }
        
        this.deviceSocket = deviceSocket;
        
        // 如果尚未连接，则连接到WebSocket服务器
        if (!this.deviceSocket.connected) {
            this.deviceSocket.connect();
        }
    }
    
    /**
     * 设置设备WebSocket事件监听器
     */
    setupDeviceSocketListeners() {
        // 检查全局deviceSocket实例是否存在
        if (typeof deviceSocket === 'undefined') {
            console.warn('SocketIOClient not available, skipping WebSocket listeners');
            return;
        }
        
        // 监听设备列表更新事件
        this.deviceSocket.on('reload_devices', (data) => {
            console.log('Received updated device list:', data);
            this.updateDeviceSelectOptions(data);
        });
        
        // 监听设备状态更新事件
        this.deviceSocket.on('device_status_update', (data) => {
            console.log('Received device status update:', data);
            this.updateDeviceStatus(data.device_id, data.status);
        });
        
        // 监听连接事件
        this.deviceSocket.on('connect', () => {
            console.log('Connected to device WebSocket server');
            this.deviceSocket.requestDeviceList();
        });
        
        // 监听断开连接事件
        this.deviceSocket.on('disconnect', (reason) => {
            console.log('Disconnected from device WebSocket server:', reason);
        });
        
        // 监听错误事件
        this.deviceSocket.on('error', (error) => {
            console.error('WebSocket error:', error);
        });
    }
    
    /**
     * 初始化刷新按钮功能
     */
    initRefreshButton() {
        // 选择设备控制区域中的第一个按钮（刷新按钮）
        const refreshButton = document.querySelector('.device-controls button:first-child');
        if (!refreshButton) return;
        
        refreshButton.addEventListener('click', () => {
            const { deviceSelectElement } = this.options;
            if (!deviceSelectElement) return;
            
            const selectedValue = deviceSelectElement.value;
            
            if (selectedValue === '0') {
                alert('请先选择设备');
                return;
            }
            
            // 如果当前有WebRTC连接，使用WebRTC刷新
            if (this.currentWebRTCClient && this.currentWebRTCClient.isConnected()) {
                this.currentWebRTCClient.requestUiTree();
                this.showUiTreeLoading();
            } else {
                // 否则使用传统方式刷新
                this.fallbackToTraditionalScreenshot(selectedValue);
            }
        });
    }
    
    /**
     * 更新设备下拉列表选项
     * @param {Array} devices - 设备列表数据
     */
    updateDeviceSelectOptions(devices) {
        if (!devices || !Array.isArray(devices)) {
            console.warn('Invalid devices data:', devices);
            return;
        }
        
        const { deviceSelectElement } = this.options;
        if (!deviceSelectElement) return;
        
        // 保存当前选中的值
        const currentValue = deviceSelectElement.value;
        
        // 清空现有选项（保留第一个默认选项）
        while (deviceSelectElement.options.length > 1) {
            deviceSelectElement.remove(1);
        }
        
        // 添加新选项
        devices.forEach(device => {
            const option = document.createElement('option');
            option.value = device.sn;
            option.textContent = device.name || device.sn;
            option.dataset.status = device.status || 'unknown';
            deviceSelectElement.appendChild(option);
        });
        
        // 尝试恢复之前选中的值
        if (currentValue) {
            deviceSelectElement.value = currentValue;
            if (deviceSelectElement.value !== currentValue) {
                deviceSelectElement.dispatchEvent(new Event('change'));
            }
        }
    }
    
    /**
     * 更新设备状态指示器
     * @param {string} deviceId - 设备ID
     * @param {string} status - 设备状态
     */
    updateDeviceStatus(deviceId, status) {
        const { deviceSelectElement } = this.options;
        
        if (deviceSelectElement) {
            for (let i = 0; i < deviceSelectElement.options.length; i++) {
                const option = deviceSelectElement.options[i];
                if (option.value === deviceId) {
                    option.dataset.status = status;
                    
                    if (deviceSelectElement.value === deviceId) {
                        const statusIndicator = document.querySelector('.device-status-indicator');
                        if (statusIndicator) {
                            statusIndicator.textContent = status;
                            statusIndicator.className = 'device-status-indicator ' + status;
                        }
                    }
                    break;
                }
            }
        }
    }
    
    /**
     * 加载设备UI控件树
     * @param {string} deviceSn - 设备序列号
     */
    loadUiElementTree(deviceSn) {
        const { uiTreeElement } = this.options;
        if (!uiTreeElement) return;
        
        // 显示加载状态
        this.showUiTreeLoading();
        
        // 如果当前有活跃的WebRTC连接，则不需要通过API获取UI树
        if (this.currentWebRTCClient && this.currentWebRTCClient.isConnected()) {
            console.log('WebRTC连接活跃，等待UI树数据通过数据通道传输');
            return;
        }
        
        // 调用API获取UI控件树数据
        window.http.get(`/api/devices?api=get_ui_tree&sn=${deviceSn}`)
            .then(response => {
                this.handleUiTreeResponse(response);
            })
            .catch(error => {
                this.handleUiTreeError(error);
            });
    }
    
    /**
     * 处理UI树响应
     * @param {Object} response - 响应对象
     */
    handleUiTreeResponse(response) {
        const { uiTreeElement } = this.options;
        
        if (response.data && response.data.uiTree) {
            this.renderUiElementTree(response.data.uiTree, uiTreeElement);
        } else if (response.data && response.data.ui_tree) {
            this.renderUiElementTree(response.data.ui_tree, uiTreeElement);
        } else if (response.data && response.data.message) {
            this.showUiTreeWarning(response.data.message);
        } else if (response.data && response.data.error === 'API_NOT_IMPLEMENTED') {
            console.log('API not implemented, using mock data');
            const mockData = this.getMockUiTree();
            this.renderUiElementTree(mockData, uiTreeElement);
        }
    }
    
    /**
     * 处理UI树错误
     * @param {Error} error - 错误对象
     */
    handleUiTreeError(error) {
        console.error('Error fetching UI tree:', error);
        
        let errorMessage = '获取UI控件树失败';
        
        if (error.response && error.response.data) {
            if (error.response.data.message) {
                errorMessage = error.response.data.message;
            } else if (typeof error.response.data === 'string') {
                errorMessage = error.response.data;
            }
        } else if (error.message) {
            errorMessage = error.message;
        }
        
        this.showUiTreeWarning(errorMessage);
        
        // 如果API尚未实现，使用模拟数据（仅用于开发测试）
        if (error.response && error.response.status === 404) {
            console.log('API not implemented, using mock data');
            setTimeout(() => {
                const mockUiTree = this.generateMockUiTree();
                this.renderUiElementTree(mockUiTree, uiTreeElement);
            }, 1000);
        }
    }
    
    /**
     * 渲染UI控件树
     * @param {Object} uiTreeData - UI树数据
     * @param {HTMLElement} container - 容器元素
     */
    renderUiElementTree(uiTreeData, container) {
        // 使用UiViewer来渲染UI控件树
        if (this.uiViewer) {
            if (!uiTreeData) {
                this.uiViewer.showEmpty('暂无UI控件树数据');
            } else {
                this.uiViewer.renderTree(uiTreeData);
            }
        } else {
            console.warn('UiViewer not initialized');
        }
        
        // 通知外部组件
        if (this.options.onUiTreeUpdate) {
            this.options.onUiTreeUpdate(uiTreeData);
        }
    }
    

    
    /**
     * 获取当前选中的设备
     * @returns {string|null} 当前选中的设备序列号
     */
    getCurrentDevice() {
        const { deviceSelectElement } = this.options;
        if (!deviceSelectElement || deviceSelectElement.value === '0') {
            return null;
        }
        return deviceSelectElement.value;
    }
    
    /**
     * 获取当前WebRTC客户端
     * @returns {Object|null} 当前WebRTC客户端实例
     */
    getCurrentWebRTCClient() {
        return this.currentWebRTCClient;
    }
    
    /**
     * 断开当前设备连接
     */
    disconnect() {
        if (this.currentWebRTCClient) {
            this.currentWebRTCClient.webrtc_disconnect();
            this.currentWebRTCClient = null;
        }
    }
    
    /**
     * 销毁设备选择器
     */
    destroy() {
        this.disconnect();
        
        if (this.deviceSocket) {
            this.deviceSocket.disconnect();
            this.deviceSocket = null;
        }
    }
}